﻿using System.Dynamic;
using Basic.FormCollect;
using Basic.FormExtendService;
using Basic.FormRemoteModel;
using Basic.FormRemoteModel.PageCalculate.Model;
using Basic.UserFormService.Interface;
using Basic.UserFormService.Model;
using Basic.UserFormService.Page.Interface;
using WeDonekRpc.Helper;
using WeDonekRpc.SqlSugar;
using WeDonekRpc.SqlSugar.VirtualQuery;

namespace Basic.UserFormService.Page
{
    internal class ChartCalculate : IChartCalculate
    {
        private readonly IPageChartService _Chart;
        private readonly IAgentFormCollect _AgentForm;
        private readonly IEmpService _Emp;
        private readonly ICompanyService _Company;
        private readonly IUnitDeptService _UnitDept;
        private readonly IDictItemService _DictItem;
        private readonly ITreeDicService _TreeDic;

        public ChartCalculate ( IPageChartService chart,
            IAgentFormCollect agentForm,
            IEmpService emp,
            ICompanyService company,
            IUnitDeptService unitDept,
            IDictItemService dictItem,
            ITreeDicService treeDic )
        {
            this._Chart = chart;
            this._AgentForm = agentForm;
            this._Emp = emp;
            this._Company = company;
            this._UnitDept = unitDept;
            this._DictItem = dictItem;
            this._TreeDic = treeDic;
        }

        public ChartResult Calculate ( CalculateArg arg )
        {
            ChartBody body = this._Chart.Get(arg.Id, arg.CompanyId, arg.Extend);
            if ( body.Query == null )
            {
                return null;
            }
            QueryStruct query;
            if ( !arg.Search.IsNull() )
            {
                IWhereCol[] where = arg.Search.GetWhere(body.Cols);
                query = body.Query.Clone();
                query.Where = query.Where.Merge(where);
            }
            else
            {
                query = body.Query;
            }
            ExpandoObject[] rows = this._AgentForm.Gets(query);
            if ( rows.IsNull() )
            {
                return null;
            }
            ChartResult result = new ChartResult();
            result.Rows = rows;
            result.XLabel = this._LoadLabel(body.GroupByCol[0], rows);
            result.Segment = body.Segment;
            if ( body.GroupByCol.Length > 1 )
            {
                result.Legend = this._LoadLabel(body.GroupByCol[1], rows);
            }
            return result;
        }
        private ChartLabel _LoadLabel ( PageGroupCol col, ExpandoObject[] rows )
        {
            if ( col.FuncType == FormColumnFuncType.人员ID )
            {
                long[] empId = rows.Distinct(a =>
                {
                    return Convert.ToInt64(( (IDictionary<string, object>)a )[col.Name]);
                });
                return new ChartLabel
                {
                    Id = col.Id,
                    Name = col.Name,
                    Label = this._Emp.GetEmpName(empId).ConvertAll(c => new KeyValuePair<string, string>(c.Key.ToString(), c.Value))
                };
            }
            else if ( col.FuncType == FormColumnFuncType.公司ID )
            {
                long[] comId = rows.Distinct(a =>
                {
                    return Convert.ToInt64(( (IDictionary<string, object>)a )[col.Name]);
                });
                return new ChartLabel
                {
                    Id = col.Id,
                    Name = col.Name,
                    Label = this._Company.GetNames(comId).ConvertAll(c => new KeyValuePair<string, string>(c.Key.ToString(), c.Value))
                };
            }
            else if ( col.FuncType == FormColumnFuncType.部门单位ID )
            {
                long[] deptId = rows.Distinct(a =>
                {
                    return Convert.ToInt64(( (IDictionary<string, object>)a )[col.Name]);
                });
                return new ChartLabel
                {
                    Id = col.Id,
                    Name = col.Name,
                    Label = this._UnitDept.GetNames(deptId).ConvertAll(c => new KeyValuePair<string, string>(c.Key.ToString(), c.Value))
                };
            }
            else if ( col.FuncType == FormColumnFuncType.选项值 )
            {
                return new ChartLabel
                {
                    Id = col.Id,
                    Name = col.Name,
                    Label = col.Items.ToArray()
                };
            }
            else if ( col.FuncType == FormColumnFuncType.树形字典 )
            {
                string[] codes = rows.Distinct(a =>
                {
                    return ( (IDictionary<string, object>)a )[col.Name].ToString();
                });
                return new ChartLabel
                {
                    Id = col.Id,
                    Name = col.Name,
                    Label = this._TreeDic.GetNames(col.DicId.Value, codes).ToArray()
                };
            }
            else if ( col.FuncType == FormColumnFuncType.字典项 )
            {
                string[] codes = rows.Distinct(a =>
                {
                    return ( (IDictionary<string, object>)a )[col.Name].ToString();
                });
                return new ChartLabel
                {
                    Id = col.Id,
                    Name = col.Name,
                    Label = this._DictItem.GetNames(col.DicId.Value, codes).ToArray()
                };
            }
            string[] text = rows.Distinct(a =>
            {
                return ( (IDictionary<string, object>)a )[col.Name].ToString();
            });
            return new ChartLabel
            {
                Id = col.Id,
                Name = col.Name,
                Label = text.Select(c => new KeyValuePair<string, string>(c, c)).ToArray()
            };
        }
    }
}
